#!/usr/bin/env python
# coding=utf-8
from scpy.logger import get_logger

logger = get_logger(__file__)


# j=0
# if j == 1:
#     pj = 10
#
# import pdb
# pdb.set_trace()




def p_fun(p, num):
    s = p + num
    p = s % 10
    if p == 0:
        p = 10
    p = p * 2
    p = p % 11
    return p


def generateRegNum(num_str_list):
    '''
        for循环实现  GB/T 17710，MOD 11,10校验公式
    :param num_str_list:14位数字的字符串
    :return:14位数字的字符串加上校验位供15位
    '''
    p = 0
    if isinstance(num_str_list, basestring):
        # num_str_list = str(num_str_list)
        for num in num_str_list:
            # print num,"num"
            num = int(num)
            p = p_fun(p, num)
            # print "\t",p,"P"

        if p == 1 or p == 0:
            num_str_list_last = str(1 - int(p))
        else:
            num_str_list_last = str(10 + 1 - int(p))
        # print str15
        num_str_list_all = num_str_list + num_str_list_last
        # print str1to15
        return num_str_list_all
    else:
        raise Exception("num_str_list type error")


# NationalAdministrativeDivisionCode
# def nasd():



#
#


acity = u'重庆'


#
#
# def initProvinceCode_json(jsonFile='allProviceCode_json.json'):
#     import re
#     '''
#         由统计局下载的全国行政代码，做成xls文件后，初始化为json文件。
#         由于行政规划可能发生变化。
#         此json部分可能会持续更新。
#         输出json包含总局代码。
#
#         ***注意：国家高新区待加入
#     '''
#     import xlrd
#
#     excelData = xlrd.open_workbook('./code.xls')
#     table0 = excelData.sheets()[0]
#     allProvinceCode_list = table0.col_values(0)[1:]
#
#     allProvinceName_list = table0.col_values(1)[1:]
#     PROVINCEDICT=(
#         u'安徽',
#         u'北京',
#         u'重庆',
#         u'福建',
#         u'广东',
#         u'甘肃',
#         u'广西',
#         u'贵州',
#         u'海南',
#         u'湖北',
#         u'河北',
#         u'河南',
#         u'黑龙江',
#         u'湖南',
#         u'吉林',
#         u'江苏',
#         u'江西',
#         u'辽宁',
#         u'内蒙古',
#         u'宁夏',
#         u'青海',
#         u'陕西',
#         u'四川',
#         u'山东',
#         u'上海',
#         u'山西',
#         u'天津',
#         u'新疆',
#         u'西藏',
#         u'云南',
#         u'浙江',
#         # '全国总局',
#     )
#
#     allProviceCode_dict = {}
#
#     for acity in PROVINCEDICT:
#
#         aProvinceCode_list = []
#         aProvinceName_list = []
#         for n, aprovince in enumerate(allProvinceName_list):
#
#             res = re.compile(ur".*"+acity+ur".*").findall(aprovince)
#             if res:
#                 aProvinceCode_list.append(allProvinceCode_list[n])
#                 aProvinceName_list.append(res[0])
#         # print len(aProvinceCode_list)
#         # print len(aProvinceName_list)
#         #
#         # print aProvinceName_list
#         # print aProvinceCode_list
#         allProviceCode_dict[acity] = aProvinceCode_list
#
#     allProviceCode_dict[u'全国总局'] = ['100000']
#     # print allProviceCode_dict
#     import json
#
#     allProviceCode_json = json.dumps(allProviceCode_dict, indent=4, ensure_ascii=False)
#     print allProviceCode_json
#
#     import codecs
#     with codecs.open(jsonFile, 'w', 'utf-8') as fp:
#         fp.write(allProviceCode_json)


def readProvinceCode_json(jsonFile='allProviceCode_json.json'):
    import codecs
    with codecs.open(jsonFile, 'r', 'utf-8') as fp:
        allProviceCode_json = fp.read()

    import json
    allProviceCode_dict = json.loads(allProviceCode_json)

    return allProviceCode_dict



    # pass


# initProvinceCode_json(jsonFile='allProviceCode_json.json')

allProviceCode_dict = readProvinceCode_json(jsonFile='allProviceCode_json.json')





# 内资
# 第7位：0到3
# code7_n = xrange(0, 4)
code7_n = xrange(0, 7)
# code8_n = xrange(1, 3)
code8_n = xrange(0, 3)

code7to8_n_str_list = []
for a7_n in code7_n:
    for a8_n in code8_n:
        code7to8_n_str_list.append(str(a7_n) + str(a8_n))


# 外资
code7_w = [4, 5]
code8_w = [1, 2, 3, 4, 5]
code9_w = [0, 1, 2, 3]

code7to9_w_str_list = []
for a7_w in code7_w:
    for a8_w in code8_w:
        for a9_w in code9_w:
            code7to9_w_str_list.append(str(a7_w) + str(a8_w) + str(a9_w))


# 内资迭代器9to14
def generate9to14_n(code9to14max=100000):
    a9to14_n = 1
    while a9to14_n < code9to14max:
        yield '0' * int(len(str(code9to14max)) - len(str(a9to14_n))) + str(a9to14_n)
        a9to14_n += 1


# # 内资迭代器7to14
# def generate7to14_n(code7to8_n_str_list):
#     # for a7to8_n in code7to8_n_str_list:
#     for a7to8_n in code7to8_n_str_list[1:2]:#for test
#         for a9to14_n in generate9to14_n():
#             a7to14_n = a7to8_n + str(a9to14_n)
#             # print a7to14_n
#             yield a7to14_n




# 外资迭代器10to14
def generate10to14_w(code8to14max=10000):
    a8to14_w = 1
    while a8to14_w < code8to14max:
        yield '0' * int(len(str(code8to14max)) - len(str(a8to14_w))) + str(a8to14_w)
        a8to14_w += 1


# # 外资迭代器7to14
# def generate7to14_w():
#     # for a7to9_w in code7to9_w_str_list:
#     for a7to9_w in code7to9_w_str_list[1:2]:
#         for aa10to14_w in generate10to14_w():
#             a7to14_w = a7to9_w + str(aa10to14_w)
#             yield a7to14_w








# 如何控制停止条件

aProviceCode_list = allProviceCode_dict[acity]

# 测试某个省的某市/县
code1to6 = aProviceCode_list[0]

# 容错次数
error_num_max = 100
# error_num < error_num_max

import math



# # twoDiff = lambda x: int(x) / 2
#
# def twoDiff(x):
#     x = int(x)
#     x /= 2
#     return x



# ares = 4
#
# astart=0
#
# astop=100

# while True:
#     if ares > (astart+astop)/2:
#         astart = (astart+astop)/2 + 1
#     elif ares < (astart+astop)/2:
#         astop = (astart+astop)/2
#
#     else:
#         print (astart+astop)/2
#         break
#
#

#
#
# 测试重庆
from crawler.cq_bak.cq_getCqCompanyInfo import *

cq_class = SearchCq()





# 内资部分，重庆
for code1to6 in aProviceCode_list:
    for a7to8_n in code7to8_n_str_list:

        code9to14max = int(math.pow(10, 14 - 9 + 1)) - 1

        test_max = code9to14max

        error_num = 0

        astart = 1




        # astart9to14_n = '0'*int(len(str(code9to14max)) - len(str(astart))) + str(astart)
        # astart1to14_n = code1to6 + a7to8_n + astart9to14_n
        #
        # astart1to15_n = generateRegNum(astart1to14_n)
        #
        # astartTryTimes = 5
        # astart_res = None
        # while astartTryTimes > 0 and (not astart_res):
        #     try:
        #         print "测试 %s 类型注册号为：%s" % (code1to6 + a7to8_n,astart1to15_n)
        #         logger.info("测试 %s 类型注册号为：%s" % (code1to6 + a7to8_n,astart1to15_n))
        #         astart_res = cq_class.getCqCompanyInfo(astart1to15_n)
        #         break
        #         # if not astart_res:
        #         #     break
        #         # else:
        #         #     continue
        #     except urllib2.HTTPError,e:     # 再发送一次请求，用当前的号码
        #         logger.error(e)
        #         astartTryTimes -= 1
        #         continue
        #     except urllib2.URLError,e:      # 再发送一次请求，用当前的号码
        #         logger.error(e)
        #         astartTryTimes -= 1
        #         continue
        #     except Exception,e:             # 当前的号码加1，再发送一次请求，实际上有bug，待考虑
        #         logger.error(e)
        #         break
        #
        #
        # if astart_res:
        astop = test_max
        test_num = astop

        while True:
            # while test_num > 0 and (GetCompanyInfoTimes > 0):
            # test_res = None


            # import pdb
            # pdb.set_trace()

            # a9to14_n = test_num
            a9to14_n = test_num

            a9to14_n = '0' * int(len(str(code9to14max)) - len(str(a9to14_n))) + str(a9to14_n)

            a1to14_n = code1to6 + a7to8_n + a9to14_n

            a1to15_n = generateRegNum(a1to14_n)
            # print len(a1to15_n)
            # test_num -= 1



            print "当前测试注册号为：%s" % a1to15_n
            logger.info("当前测试注册号为：%s" % a1to15_n)

            GetCompanyInfoTimes = 5  # 重新链接网络次数
            test_res = None

            while test_num > 0 and (GetCompanyInfoTimes > 0):
                try:
                    # 调用工商
                    test_res = cq_class.getCqCompanyInfo(a1to15_n)
                    break
                    # test_res = False
                except urllib2.HTTPError, e:  # 再发送一次请求，用当前的号码
                    logger.error(e)
                    GetCompanyInfoTimes -= 1
                    continue
                except urllib2.URLError, e:  # 再发送一次请求，用当前的号码
                    logger.error(e)
                    GetCompanyInfoTimes -= 1
                    continue
                except Exception, e:  # 当前的号码加1，再发送一次请求，实际上有bug，待考虑
                    logger.error(e)
                    import traceback

                    traceback.print_exc()

                    # if astop:
                    # 待考虑
                    logger.info("目前为 %s %s , 测试工商号为 %s" % (astart, astop, test_num))
                    test_num += 1
                    continue

            print "工商结果", test_res

            if astart != astop:
                if test_res:
                    astart = (astart + astop) / 2 + 1
                    test_num = astart
                    print "目前范围为", astart, astop
                    logger.info("目前范围为 %s %s" % (astart, astop))
                else:
                    astop = (astart + astop) / 2
                    test_num = astop
                    print "目前范围为", astart, astop
                    logger.info("目前范围为 %s %s" % (astart, astop))

            else:
                # if test_res:
                test_num = (astart + astop) / 2
                print a7to8_n, "\t这种公司有%s个" % test_num
                logger.info("%s,\t这种公司有%s个" % (a7to8_n, test_num))
                break
                # else:
                #     print a7to8_n, "%s,\t这种公司有%s个" % (a7to8_n,test_num)
                #     logger.info("%s,\t这种公司有%s个" % (a7to8_n,test_num))
                # else:
                #     logger.info("%s,\t没有这种类型的公司" % a7to8_n)
                #     continue







                # print a7to8_n, "\t这种公司有多少个"



#
# #
#

# import pdb
# pdb.set_trace()
#



if __name__ == "__main__":
    '''
        测试
    '''

    # for a in generate7to14_w():
    #     print a


    #     # 110108000000016
    #     # str1to14 = '11010800000001'
    #
    #     # 441200000028834
    #     # str1to14 = '44120000002883'
    #
    #     # 500227600360296
    #     # str1to14 = '50022760036029'
    #
    #     # # 500901000031324
    #     # str1to14 = '50090100003132'
    #
    #     # #  500905008126747
    #     # str1to14 = '50090500812674'
    #
    #     # #  500905008064716
    #     # str1to14 = '50090500806471'
    #
    #     # str1to14 = '50090500000011'
    #     编号从1开始
    #     str1to14 = '50090500000000'
    #
    #     #  500000400067181
    str1to14 = '50000040006718'
    str1to14 = '50000002999999'
    #
    print generateRegNum(str1to14)
